package com.woniu.commentorder.console;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson2.JSON;
import com.hc.entity.Goods;
import com.hc.vo.UtilClass;
import com.woniu.commentorder.service.GoodService;
import io.seata.spring.annotation.GlobalTransactional;
import io.seata.tm.api.GlobalTransactionContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.InvalidClassException;

@RestController
@RequestMapping("Goods")
@Slf4j
public class GoodsConsole {
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private GoodService goodService;

    @PostMapping("/de")
//    @GlobalTransactional
    public String decstock(@RequestBody UtilClass utilClass) throws InvalidClassException {
//        goodService.destock(utilClass.getNum(),utilClass.getId());
        String xid = GlobalTransactionContext.getCurrentOrCreate().getXid();
        System.out.println("gaifuwudeXID"+xid);
//        if (2 > 1) {
//            throw new InvalidClassException("测试跑得异常");
//        }
        goodService.destock(utilClass.getNum(), utilClass.getId());
        log.info("进入消息队列");
//        return (String) rabbitTemplate.convertSendAndReceive("orderexchange", "decrease.goods.afdad", JSON.toJSONString(utilClass));
        return "操作成功";
    }

    @PostMapping("/in")
    @SentinelResource(value = "incr", blockHandler = "doOnBlock")
    public String incstock(@RequestBody UtilClass utilClass) throws InterruptedException {
//        goodService.destock(utilClass.getNum(),utilClass.getId());
//        if (2 > 1) {
//            throw new InterruptedException();
//        }
        log.info("进入消息队列");
        return (String) rabbitTemplate.convertSendAndReceive("orderexchange", "increase.goods.afdad", JSON.toJSONString(utilClass));
    }

    public String doOnBlock(@RequestBody UtilClass utilClass, BlockException exception) throws InterruptedException {
        System.out.println("降级");
        return "已经降级";
    }

    @PostMapping("/getbyid")
    @GlobalTransactional
    public Goods getById(@RequestBody Goods goods) {
        return goodService.getById(goods.getId());
    }
}
